<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');
// +----------------------------------------------------------------------+
// | Treacle PHP Framework Version 0.10                                   |
// +----------------------------------------------------------------------+
// | Copyright (c) 2007 Treacle.cn All rights reserved.					  |
// +----------------------------------------------------------------------+
// | Licensed under the Apache License, Version 2.0 (the 'License');      |
// | you may not use this file except in compliance with the License.     |
// | You may obtain a copy of the License at                              |
// | http://www.apache.org/licenses/LICENSE-2.0                           |
// | Unless required by applicable law or agreed to in writing, software  |
// | distributed under the License is distributed on an 'AS IS' BASIS,    |
// | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or      |
// | implied. See the License for the specific language governing         |
// | permissions and limitations under the License.                       |
// +----------------------------------------------------------------------+
// | Author: BoPo <ibopo@126.com>										  |
// +----------------------------------------------------------------------+
/**
 * 数据输入处理类文件
 *
 * @author BoPo <ibopo@126.com>
 * @link http://www.treacle.cn/
 * @copyright Copyright &copy; 2007 Treacle
 * @license http://www.treacle.cn/license/
 * @version $Id $
 * @package libraries
 */
/**
 * 数据输入处理类
 *
 * @package libraries
 * @author BoPo <ibopo@126.com>
 * @since 0.10
 * @version	$Id $
 */
final class TInput
{
	private $use_xss_clean		= false;
	private $ip_address			= false;
	private $user_agent			= false;
	private $allow_get_array	= false;
	/**
	 * 构造函数
	 *
	 * @access	public
	 */
	public function __construct()
	{
		$this->config			= Configure::item_array();
		$this->use_xss_clean	= ($this->config['global_xss_filtering'] === true) ? true : false;
		$this->allow_get_array	= ($this->config['enable_query_strings'] === true) ? true : false;
		$this->_sanitize_globals();
	}

	/**
	 * 清理全局变量的非法字符
	 * @access	private
	 * @return	void
	 */
	private function _sanitize_globals()
	{
		// Unset globals. This is effectively the same as register_globals = off
		foreach (array($_GET, $_POST, $_COOKIE) as $global)
		{
			if ( ! is_array($global))
			{
				global $global;
				$$global = NULL;
			}
			else
			{
				foreach ($global as $key => $val)
				{
					global $$key;
					$$key = NULL;
				}
			}
		}

		// Is $_GET data allowed? If not we'll set the $_GET to an empty array
		if ($this->allow_get_array == false)
		{
			$_GET = array();
		}

		// Clean $_POST Data
		if (is_array($_POST) AND count($_POST) > 0)
		{
			foreach($_POST as $key => $val)
			{
				$_POST[$this->_clean_input_keys($key)] = $this->_clean_input_data($val);
			}
		}

		// Clean $_COOKIE Data
		if (is_array($_COOKIE) AND count($_COOKIE) > 0)
		{
			foreach($_COOKIE as $key => $val)
			{
				$_COOKIE[$this->_clean_input_keys($key)] = $this->_clean_input_data($val);
			}
		}
	}

	/**
	 * 清理输入数据
	 * @access	private
	 * @param	string
	 * @return	string
	 */
	private function _clean_input_data($str)
	{
		if (is_array($str))
		{
			$new_array = array();
			foreach ($str as $key => $val)
			{
				$new_array[$this->_clean_input_keys($key)] = $this->_clean_input_data($val);
			}
			return $new_array;
		}
		if ($this->use_xss_clean === true)
		{
			$str = $this->xss_clean($str);
		}
		return preg_replace("/\015\012|\015|\012/", "\n", $str);
	}
	/**
	 * Clean Keys
	 *
	 * @access	private
	 * @param	string
	 * @return	string
	 */
	private function _clean_input_keys($str)
	{
		if ( ! preg_match("/^[a-z0-9:_\/-]+$/i", $str))
		{
			exit('Disallowed Key Characters: '.$str);
		}
		if ( ! get_magic_quotes_gpc())
		{
			return addslashes($str);
		}
		return $str;
	}

	/**
	 * 获取一个 POST 的值
	 * @access	public
	 * @param	string
	 * @param	bool
	 * @return	string
	 */
	public function post($index = '', $xss_clean = false)
	{
		if ( ! isset($_POST[$index]))
		{
			return false;
		}
		if ($xss_clean === true)
		{
			if (is_array($_POST[$index]))
			{
				foreach($_POST[$index] as $key => $val)
				{
					$_POST[$index][$key] = $this->xss_clean($val);
				}
			}
			else
			{
				return $this->xss_clean($_POST[$index]);
			}
		}
		else
		{
			return $_POST[$index];
		}
	}

	/**
	 * 获取一个 COOKIE 的数据
	 * @access	public
	 * @param	string
	 * @param	bool
	 * @return	string
	 */
	public function cookie($index = '', $xss_clean = false)
	{
		if ( ! isset($_COOKIE[$index]))
		{
			return false;
		}

		if ($xss_clean === true)
		{
			if (is_array($_COOKIE[$index]))
			{
				$cookie = array();
				foreach($_COOKIE[$index] as $key => $val)
				{
					$cookie[$key] = $this->xss_clean($val);
				}
				return $cookie;
			}
			else
			{
				return $this->xss_clean($_COOKIE[$index]);
			}
		}
		else
		{
			return $_COOKIE[$index];
		}
	}

	/**
	 * 活动一个 SERVER 数组
	 * @access	public
	 * @param	string
	 * @param	bool
	 * @return	string
	 */
	public function server($index = '', $xss_clean = false)
	{
		if ( ! isset($_SERVER[$index]))
		{
			return false;
		}
		if ($xss_clean === true)
		{
			return $this->xss_clean($_SERVER[$index]);
		}
		return $_SERVER[$index];
	}

	/**
	 * 获取一个 IP 地址
	 * @access	public
	 * @return	string
	 */
	public function ip_address()
	{
		if ($this->ip_address !== false)
		{
			return $this->ip_address;
		}
		if ($this->server('REMOTE_ADDR') AND $this->server('HTTP_CLIENT_IP'))
		{
			$this->ip_address = $_SERVER['HTTP_CLIENT_IP'];
		}
		elseif ($this->server('REMOTE_ADDR'))
		{
			$this->ip_address = $_SERVER['REMOTE_ADDR'];
		}
		elseif ($this->server('HTTP_CLIENT_IP'))
		{
			$this->ip_address = $_SERVER['HTTP_CLIENT_IP'];
		}
		elseif ($this->server('HTTP_X_FORWARDED_FOR'))
		{
			$this->ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
		}
		if ($this->ip_address === false)
		{
			$this->ip_address = '0.0.0.0';
			return $this->ip_address;
		}
		if (strstr($this->ip_address, ','))
		{
			$x = explode(',', $this->ip_address);
			$this->ip_address = end($x);
		}
		if ( ! $this->valid_ip($this->ip_address))
		{
			$this->ip_address = '0.0.0.0';
		}
		return $this->ip_address;
	}

	/**
	 * 验证 IP 地址
	 * @access	public
	 * @param	string
	 * @return	string
	 */
	public function valid_ip($ip)
	{
		return ( ! preg_match( "/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/", $ip)) ? false : true;
	}

	/**
	 * 获取浏览器的 UserAgent
	 *
	 * @access	public
	 * @return	string
	 */
	public function user_agent()
	{
		if ($this->user_agent !== false)
		{
			return $this->user_agent;
		}
		$this->user_agent = ( ! isset($_SERVER['HTTP_USER_AGENT'])) ? false : $_SERVER['HTTP_USER_AGENT'];
		return $this->user_agent;
	}

	/**
	 * XSS Clean 跨站脚本攻击过滤
	 * @access	public
	 * @param	string
	 * @return	string
	 */
	public function xss_clean($str, $charset = 'UTF-8')
	{
		/*
		* Remove Null Characters
		*
		* This prevents sandwiching null characters
		* between ascii characters, like Java\0script.
		*
		*/
		$str = preg_replace('/\0+/', '', $str);
		$str = preg_replace('/(\\\\0)+/', '', $str);
		/*
		* Validate standard character entities
		*
		* Add a semicolon if missing.  We do this to enable
		* the conversion of entities to ASCII later.
		*
		*/
		$str = preg_replace('#(&\#*\w+)[\x00-\x20]+;#u',"\\1;",$str);
		/*
		* Validate UTF16 two byte encoding (x00)
		*
		* Just as above, adds a semicolon if missing.
		*
		*/
		$str = preg_replace('#(&\#x*)([0-9A-F]+);*#iu',"\\1\\2;",$str);
		/*
		* URL Decode
		*
		* Just in case stuff like this is submitted:
		*
		* <a href="http://%77%77%77%2E%67%6F%6F%67%6C%65%2E%63%6F%6D">Google</a>
		*
		* Note: Normally urldecode() would be easier but it removes plus signs
		*
		*/
		$str = preg_replace("/%u0([a-z0-9]{3})/i", "&#x\\1;", $str);
		$str = preg_replace("/%([a-z0-9]{2})/i", "&#x\\1;", $str);
		/*
		* Convert character entities to ASCII
		*
		* This permits our tests below to work reliably.
		* We only convert entities that are within tags since
		* these are the ones that will pose security problems.
		*
		*/
		if (preg_match_all("/<(.+?)>/si", $str, $matches))
		{
			for ($i = 0; $i < count($matches['0']); $i++)
			{
				$str = str_replace($matches['1'][$i],
				$this->_html_entity_decode($matches['1'][$i], $charset),
				$str);
			}
		}

		/*
		* Convert all tabs to spaces
		*
		* This prevents strings like this: ja	vascript
		* Note: we deal with spaces between characters later.
		*
		*/
		$str = preg_replace("#\t+#", " ", $str);

		/*
		* Makes PHP tags safe
		*
		*  Note: XML tags are inadvertently replaced too:
		*
		*	<?xml
		*
		* But it doesn't seem to pose a problem.
		*
		*/
		$str = str_replace(array('<?php', '<?PHP', '<?', '?>'),  array('&lt;?php', '&lt;?PHP', '&lt;?', '?&gt;'), $str);

		/*
		* Compact any exploded words
		*
		* This corrects words like:  j a v a s c r i p t
		* These words are compacted back to their correct state.
		*
		*/
		$words = array('javascript', 'vbscript', 'script', 'applet', 'alert', 'document', 'write', 'cookie', 'window');

		foreach ($words as $word)
		{
			$temp = '';
			for ($i = 0; $i < strlen($word); $i++)
			{
				$temp .= substr($word, $i, 1)."\s*";
			}
			$temp = substr($temp, 0, -3);
			$str = preg_replace('#'.$temp.'#s', $word, $str);
			$str = preg_replace('#'.ucfirst($temp).'#s', ucfirst($word), $str);
		}

		/*
		* Remove disallowed Javascript in links or img tags
		*/
		$str = preg_replace("#<a.+?href=.*?(alert\(|alert&\#40;|javascript\:|window\.|document\.|\.cookie|<script|<xss).*?\>.*?</a>#si", "", $str);
		$str = preg_replace("#<img.+?src=.*?(alert\(|alert&\#40;|javascript\:|window\.|document\.|\.cookie|<script|<xss).*?\>#si", "", $str);
		$str = preg_replace("#<(script|xss).*?\>#si", "", $str);

		/*
		* Remove JavaScript Event Handlers
		*
		* Note: This code is a little blunt.  It removes
		* the event handler and anything up to the closing >,
		* but it's unlikely to be a problem.
		*
		*/
		$str = preg_replace('#(<[^>]+.*?)(onblur|onchange|onclick|onfocus|onload|onmouseover|onmouseup|onmousedown|onselect|onsubmit|onunload|onkeypress|onkeydown|onkeyup|onresize)[^>]*>#iU',"\\1>",$str);

		/*
		* Sanitize naughty HTML elements
		*
		* If a tag containing any of the words in the list
		* below is found, the tag gets converted to entities.
		*
		* So this: <blink>
		* Becomes: &lt;blink&gt;
		*
		*/
		$str = preg_replace('#<(/*\s*)(alert|applet|basefont|base|behavior|bgsound|blink|body|embed|expression|form|frameset|frame|head|html|ilayer|iframe|input|layer|link|meta|object|plaintext|style|script|textarea|title|xml|xss)([^>]*)>#is', "&lt;\\1\\2\\3&gt;", $str);
		/*
		* Sanitize naughty scripting elements
		*
		* Similar to above, only instead of looking for
		* tags it looks for PHP and JavaScript commands
		* that are disallowed.  Rather than removing the
		* code, it simply converts the parenthesis to entities
		* rendering the code un-executable.
		*
		* For example:	eval('some code')
		* Becomes:		eval&#40;'some code'&#41;
		*
		*/
		$str = preg_replace('#(alert|cmd|passthru|eval|exec|system|fopen|fsockopen|file|file_get_contents|readfile|unlink)(\s*)\((.*?)\)#si', "\\1\\2&#40;\\3&#41;", $str);

		/*
		* Final clean up
		*
		* This adds a bit of extra precaution in case
		* something got through the above filters
		*
		*/
		$bad = array(
		'document.cookie'	=> '',
		'document.write'	=> '',
		'window.location'	=> '',
		"javascript\s*:"	=> '',
		"Redirect\s+302"	=> '',
		'<!--'				=> '&lt;!--',
		'-->'				=> '--&gt;'
		);

		foreach ($bad as $key => $val)
		{
			$str = preg_replace("#".$key."#i", $val, $str);
		}
		return $str;
	}

	/**
	 * HTML 标签解码
	 * @access	private
	 * @param	string
	 * @param	string
	 * @return	string
	 */
	private function _html_entity_decode($str, $charset='utf-8')
	{
		if (stristr($str, '&') === false) return $str;

		// The reason we are not using html_entity_decode() by itself is because
		// while it is not technically correct to leave out the semicolon
		// at the end of an entity most browsers will still interpret the entity
		// correctly.  html_entity_decode() does not convert entities without
		// semicolons, so we are left with our own little solution here. Bummer.

		if (function_exists('html_entity_decode') && (strtolower($charset) != 'utf-8' OR version_compare(phpversion(), '5.0.0', '>=')))
		{
			$str = html_entity_decode($str, ENT_COMPAT, $charset);
			$str = preg_replace('~&#x([0-9a-f]{2,5})~ei', 'chr(hexdec("\\1"))', $str);
			return preg_replace('~&#([0-9]{2,4})~e', 'chr(\\1)', $str);
		}

		// Numeric Entities
		$str = preg_replace('~&#x([0-9a-f]{2,5});{0,1}~ei', 'chr(hexdec("\\1"))', $str);
		$str = preg_replace('~&#([0-9]{2,4});{0,1}~e', 'chr(\\1)', $str);

		// Literal Entities - Slightly slow so we do another check
		if (stristr($str, '&') === false)
		{
			$str = strtr($str, array_flip(get_html_translation_table(HTML_ENTITIES)));
		}
		return $str;
	}
}
/*
+---------------------------------------------------------------------------
|   Last Modified By BoPo
|   Date: Wed Nov 07 23:55:45 CST 2007
+--------------------------------------------------------------------------
*/
?>